<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <!--          <template #left>-->
          <!--            <el-button @click="showDialog('add')" :icon="Plus" v-ripple>新增</el-button>-->
          <!--          </template>-->
        </ArtTableHeader>

        <art-table
          :data="tableData"
          :loading="loading"
          v-model:currentPage="queryParams.page"
          v-model:pageSize="queryParams.size"
          :total="total"
          @size-change="getTableData"
          @current-change="getTableData"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
          width="40%"
          top="5vh"
        >
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="简介" prop="desc">
              <el-input v-model="formData.desc" placeholder="请输入商品简介" />
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <ArtImageUpload v-model:files="formData.cover"></ArtImageUpload>
            </el-form-item>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="是否是新品" prop="is_news">
                  <el-radio-group v-model="formData.is_news">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="-1">不是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否折扣商品" prop="is_discount">
                  <el-radio-group v-model="formData.is_discount">
                    <el-radio :value="1">是</el-radio>
                    <el-radio :value="-1">不是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="现价" prop="price">
                  <el-input
                    v-model="formData.price"
                    placeholder="请输入现价"
                    :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原价" prop="origin_price">
                  <el-input
                    v-model="formData.origin_price"
                    placeholder="请输入原价"
                    :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                    :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="销售数量" prop="sell_num">
                  <el-input-number
                    v-model="formData.sell_num"
                    style="width: 100%"
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存" prop="inventory">
                  <el-input-number
                    v-model="formData.inventory"
                    style="width: 100%"
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="上架状态" prop="state">
                  <el-tooltip :content="formData.state === 1 ? '上架' : '下架'" placement="top">
                    <el-switch
                      v-model="formData.state"
                      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                      :active-value="1"
                      :inactive-value="-1"
                    />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort">
                  <el-input-number v-model="formData.sort" :min="1" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="内容" prop="content">
              <el-input type="textarea" v-model="formData.content" placeholder="请输入商品内容" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
      <AnnexGoods ref="annexRef" :type="1"></AnnexGoods>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { ElButton, FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage, ElTag } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { GoodsService } from '@/api/goods'
  import { Delete, Document, Edit } from '@element-plus/icons-vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const tableData = ref<any>([])
  const total = ref(0)
  const annexRef = ref(null)

  const formData = reactive({
    name: '',
    desc: '',
    cover: '',
    price: '',
    origin_price: '',
    sell_num: 0,
    inventory: 0,
    state: 1,
    sort: 10,
    content: '',
    is_news: 1,
    is_discount: 1
  })

  const queryParams = reactive({
    page: 1,
    size: 10,
    discount: 1
  })

  const loading = ref(false)

  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: '名称', prop: 'name' },
    { label: '封面', prop: 'cover' },
    { label: '现价', prop: 'price' },
    { label: '原价', prop: 'origin_price' },
    { label: '销售数量', prop: 'sell_num' },
    { label: '库存', prop: 'inventory' },
    { label: '简介', prop: 'desc' },
    { label: '内容', prop: 'content' },
    { label: '上架状态', prop: 'state' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    // { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    // { type: 'index', label: '序号', width: 80 }, // 序号列
    { prop: 'name', label: '名称', align: 'center' },
    {
      prop: 'cover',
      label: '封面',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.cover })
      }
    },
    { prop: 'price', label: '现价' },
    { prop: 'origin_price', label: '原价' },
    { prop: 'sell_num', label: '销售数量' },
    { prop: 'inventory', label: '库存' },
    { prop: 'desc', label: '描述', align: 'center' },
    { prop: 'content', label: '内容', align: 'center' },
    {
      prop: 'state',
      label: '上架状态',
      formatter: (row: any) => {
        return h(ElTag, { type: getTagType(row.state) }, () => buildTagText(row.state))
      }
    },
    {
      prop: 'create_time',
      label: '创建日期',
      width: 160,
      align: 'center',
      sortable: true
    },
    {
      prop: 'operation',
      label: '操作',
      align: 'center',
      width: 210,
      fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', { class: 'option' }, [
          h(
            ElButton,
            {
              size: 'small',
              icon: Edit,
              text: true,
              onClick: () => showDialog('edit', row)
            },
            () => '编辑'
          ),
          h(
            ElButton,
            {
              size: 'small',
              type: 'danger',
              icon: Delete,
              text: true,
              onClick: () => deleteTableRow(row)
            },
            () => '删除'
          ),
          h(
            ElButton,
            {
              size: 'small',
              icon: Document,
              text: true,
              onClick: () => showAnnex(row)
            },
            () => '附件'
          )
        ])
      }
    }
  ])

  // 显示附件弹窗
  const showAnnex = (row: any) => {
    annexRef.value.openList(row.id, row.cover)
  }

  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const { data } = await GoodsService.getGoods(queryParams)
    tableData.value = data.data.filter((item: any) => item.state !== -2)
    total.value = tableData.value.length
    loading.value = false
  }

  onMounted(() => {
    getTableData()
  })

  const handleRefresh = () => {
    getTableData()
  }
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      formData.name = row.name
      formData.cover = row.cover
      formData.price = row.price
      formData.origin_price = row.origin_price
      formData.desc = row.desc
      formData.sell_num = row.sell_num
      formData.inventory = row.inventory
      formData.content = row.content
      formData.state = row.state
      formData.is_news = row.is_news
      formData.is_discount = row.is_discount
      formData.id = row.id
    } else {
      formData.name = ''
      formData.price = ''
      formData.origin_price = ''
      formData.cover = ''
      formData.desc = ''
      formData.sell_num = 0
      formData.inventory = 0
      formData.content = ''
      formData.is_news = 1
      formData.is_discount = 1
      formData.state = 1
      formData.id = ''
    }
  }

  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该商品吗？', '删除商品', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return GoodsService.delGoods(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const getTagType = (state: number) => {
    switch (state) {
      case 1:
        return 'success'
      case -1:
        return 'danger'
      default:
        return 'info'
    }
  }

  const buildTagText = (status: number) => {
    let text = ''
    if (status === 1) {
      text = '上架'
    } else if (status === -1) {
      text = '下架'
    }
    return text
  }

  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入商品简介', trigger: 'blur' }],
    cover: [{ required: true, message: '请选择商品封面', trigger: 'blur' }],
    price: [{ required: true, message: '请输入商品现格', trigger: 'blur' }],
    origin_price: [{ required: true, message: '请输入商品原价', trigger: 'blur' }],
    sell_num: [{ required: true, message: '请输入商品销售数量', trigger: 'blur' }],
    inventory: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
    content: [{ required: true, message: '请输入商品内容', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await GoodsService.addGoods(formData)
        } else {
          await GoodsService.updateGoods(formData)
        }
        await getTableData()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
</style>
